package com.youyicloud.api;

import com.alibaba.fastjson.JSONObject;
import com.youyicloud.constants.Constants;
import com.youyicloud.entity.SmsConfig;
import com.youyicloud.service.OssService;
import com.youyicloud.service.SmsConfigService;
import com.youyicloud.utils.CommonUtils;
import com.youyicloud.vo.ResponseBodyEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("aliSms")
@Slf4j
public class AliSmsApi {

    @Autowired
    private SmsConfigService smsConfigService;

    /**
     * 阿里发送短信接口
     * @param phoneNum 手机号
     * @param appId
     * @param templateCode 模板ID
     * @return
     * @throws Exception
     */
    @RequestMapping("/send")
    public ResponseBodyEntity ossSign(String phoneNum,String appId,String templateCode) throws Exception{
        ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
        responseBodyEntity.setState(Constants.FAILURE);
        if (StringUtils.isEmpty(phoneNum)) {
            responseBodyEntity.setMsg("发送短信的手机号不能为空");
        }
        List<SmsConfig> smsConfigs = smsConfigService.findByAppId(appId);
        if (smsConfigs.size() > 0) {
            SmsConfig smsConfig = smsConfigs.get(0);
            String securityCode = CommonUtils.getRandomString(6);
            boolean flag = smsConfigService.send(smsConfig,phoneNum,templateCode,securityCode);
            if (flag) {
                responseBodyEntity.setMsg("发送成功");
                Map<String,String> map = new HashMap<String,String>();
                map.put("securityCode",securityCode);
                map.put("phoneNum",phoneNum);
                responseBodyEntity.setData(map);
                responseBodyEntity.setState(Constants.SUCCEED);
            }else {
                responseBodyEntity.setMsg("发送短信失败");
                log.info("发送短信失败:{}",phoneNum);
            }
        }else {
            responseBodyEntity.setMsg("未找到 "+appId + "的相关配置信息");
        }
        return responseBodyEntity;
    }

}
